package com.xl.rentkeeper.web;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.xl.rentkeeper.R;
import com.xl.rentkeeper.act.BaseAct;
import com.xl.rentkeeper.log.QLog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * Created by zwc on 2015/7/6.
 */
public class WebEntry extends BaseAct{
    WebView wv;
    public static final String Param_Url = "param_url";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_webview);
        wv = (WebView)findViewById(R.id.wv);
        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        wv.setWebChromeClient(
                new ChromeClient()
        );
        wv.setWebViewClient(new WebClient());
        String url = getIntent().getStringExtra(Param_Url);
        if (TextUtils.isEmpty(url)) {
            url = "file:///android_asset/test.html";
        }
         wv.loadUrl(url);

//        wv.loadUrl("http://www.baidu.com");
    }

    @Override
    public void onBackPressed() {
        if (wv.copyBackForwardList().getCurrentIndex() > 0) {
            wv.goBack();
        }
        else {
            super.onBackPressed(); // finishes activity
        }
    }

    public class ChromeClient extends InjectedChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setMessage(message);
            builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create();
            builder.show();
            return false;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }


    private static final String INJECTION_TOKEN = "inject_js/";
    public class WebClient extends WebViewClient {
        boolean inject = false;
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            QLog.d(this,"onPageStarted");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            QLog.d(this, "onPageFinished");
            if (!inject) {
                injectJs(view);
                inject = true;
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            QLog.d(this, "shouldOverrideUrlLoading " + url);
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            QLog.d(this, "shouldInterceptRequest " + url);
            WebResourceResponse response =  super.shouldInterceptRequest(view, url);
            if(url != null && url.contains(INJECTION_TOKEN)) {
                String assetPath = url.substring(url.indexOf(INJECTION_TOKEN) + INJECTION_TOKEN.length(), url.length());
                try {
                    response = new WebResourceResponse(
                            "application/javascript",
                            "UTF8",
                            view.getContext().getAssets().open(assetPath)
                    );
                } catch (IOException e) {
                    e.printStackTrace(); // Failed to load asset file
                }
            }
            return response;
        }

    }

    private void loadJs(WebView view,String path) {
        try {
            InputStream ins = getAssets().open(path);
            BufferedReader in=
                    new BufferedReader(new InputStreamReader(ins));
            String str;
            StringBuilder buf=new StringBuilder();
            buf.append("javascript:");
            while ((str=in.readLine()) != null) {
                buf.append(str);
            }
            view.loadUrl(buf.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void injectJs(WebView view) {
        loadJs(view,"android.js");
        view.loadUrl("javascript:addJsFile('inject_js/bridge.js')");
        view.loadUrl("javascript:addJsFile('inject_js/HostApi.js')");
    }

    @Override
    public boolean onBack(int keyCode, KeyEvent event) {
        return true;
    }
}
